package jp.co.jbuy.listener;

import java.util.UUID;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import jp.co.jbuy.util.MD5;

/**
 * 与Session实现一对一绑定
 * @author songyx
 */
public class SessionBindingListener implements HttpSessionBindingListener {
	
	@Override
	public void valueBound(HttpSessionBindingEvent event) {
		
		HttpSession session = event.getSession();
		
		try {
			
			// 用SessionId和UUID进行 MD5 加密
			String captcha = MD5.digestMd5(session.getId() + UUID.randomUUID());
			
			// 将加密后的验证码放入Session中
			session.setAttribute("session_captcha", captcha);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void valueUnbound(HttpSessionBindingEvent event) {
		
		HttpSession session = event.getSession();
		// 将Session中的加密字符串移走
		session.removeAttribute("session_captcha");
	}
}
